package com.coffee.mongodb;


import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mongo.MongoClientFactory;
import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoTransactionManager;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.stream.Collectors;

/**
 * @author: songkui
 * @since: 2022/5/6 10:23
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(MongoClient.class)
@EnableConfigurationProperties(MongoProperties.class)
@ConditionalOnMissingBean(type = "org.springframework.data.mongodb.MongoDatabaseFactory")
public class MochaMongoConfiguration {

    @Bean
    @ConditionalOnMissingBean(MongoClient.class)
    public MongoClient mongo(ObjectProvider<MongoClientSettingsBuilderCustomizer> builderCustomizers,
                             MongoClientSettings settings) {
        return new MongoClientFactory(builderCustomizers.orderedStream().collect(Collectors.toList()))
                .createMongoClient(settings);
    }

    /**
     * mongodb 独立部署加事务就会报错；UncategorizedMongoDbException: This MongoDB deployment does not support retryable writes.
     * 解决办法： mongodb需要加副本集； 非独立运行；事务才有效；
     * @param factory
     * @return
     */
    @Bean(name = "mongoTransactionManager")
    public MongoTransactionManager mongoTransactionManager(MongoDatabaseFactory factory){
        return new MongoTransactionManager(factory);
    }


    @Bean
    public MochaMongoTemplate mochaMongoTemplate(MongoTemplate mongoTemplate)
    {
        return new MochaMongoTemplate(mongoTemplate);
    }


}

